package com.hsd.znsh.controller.manager;

import com.hsd.znsh.entity.Product;
import com.hsd.znsh.entity.ProductType;
import com.hsd.znsh.exception.ZnshException;
import com.hsd.znsh.pojo.output.ProductVO;
import com.hsd.znsh.pojo.output.ResultVO;
import com.hsd.znsh.pojo.query.ProductQuery;
import com.hsd.znsh.properties.SecurityProperties;
import com.hsd.znsh.repository.ProductRepository;
import com.hsd.znsh.repository.ProductTypeRepository;
import com.hsd.znsh.service.ProductService;
import com.hsd.znsh.service.ProductTypeService;
import com.hsd.znsh.utils.FileUtil;
import com.hsd.znsh.utils.ResultVOUtil;
import com.hsd.znsh.utils.SecurityUtil;
import com.hsd.znsh.utils.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/*
 * @auther: wangjiacai
 *
 * @create: 2018-04-26 11:15:50
 */
@RestController
@RequestMapping("/manager/product")
public class ManagerProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductTypeRepository productTypeRepository;

    @Autowired
    private SecurityProperties securityProperties;

    @GetMapping("/getProductList")
    public ResultVO getProductListTotalPages(Integer size,ProductQuery productQuery){
        long totalNum;
        if(SecurityUtil.hasRole("ROLE_ROOT")){
            totalNum=productService.getProductListTotalPages(productQuery,null);
        }else{
            totalNum=productService.getProductListTotalPages(productQuery,SecurityUtil.getUserId());
        }
        return ResultVOUtil.success((long)Math.ceil(totalNum/(double)size));

    }

    @PostMapping("/getProductList")
    public ResultVO getProductList(Pageable pageable,ProductQuery productQuery){
        List<ProductVO> list;
        if(SecurityUtil.hasRole("ROLE_ROOT")){
            list=productService.getProductList(pageable,productQuery,null);
        }else{
            list=productService.getProductList(pageable,productQuery,SecurityUtil.getUserId());
        }
        return ResultVOUtil.success(list);
    }

    @GetMapping("/getProductInfo")
    public ResultVO getProductInfo(Integer id){
        ProductVO productVO=productService.getProductInfo(id);
        return ResultVOUtil.success(productVO);
    }

    @PostMapping("/editProduct")
    public ResultVO editProduct(@RequestParam(name = "file",required = false) MultipartFile multipartFile,
                                @Valid Product product, BindingResult bindingResult){
        ValidatorUtil.valid(bindingResult);
        if(product.getId()==null){
            productService.addProduct(product,multipartFile);
            return ResultVOUtil.success("添加成功");
        }else{
            productService.updateProduct(product,multipartFile);
            return ResultVOUtil.success("修改成功");
        }
    }

    @PostMapping("/deleteProduct")
    public ResultVO deleteProduct(Integer id){
        productService.deleteProduct(id);
        return ResultVOUtil.success("删除成功");
    }

    @GetMapping("/getProductTypeByName")
    public List<ProductType> getProductTypeByName(String name){
        List<Integer> parents=productTypeRepository.findParentIdList();
        return productTypeRepository.findByNameLikeAndIdNotIn("%"+name+"%",parents);
    }

    @GetMapping("/getProductImage")
    public ResponseEntity<byte[]> getImage(String path)  throws IOException {
        String filePath=securityProperties.getBrowser().getFilePath();
        if(!path.startsWith(filePath+"/product")) throw new ZnshException(500,"文件路径不正确");
        InputStream inputStream=new FileInputStream(path);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        byte[] bytes=StreamUtils.copyToByteArray(inputStream);
        inputStream.close();
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
    }
}
